﻿using System.Collections.Generic;
using System.ComponentModel.Composition;

namespace MyConsoleApp.Code
{
    /*
    class Program
    {
        private static CompositionContainer _container;
        static void Main(string[] args)
        {
            Console.WriteLine("Hello World in osc@git");

            var catalog = new AssemblyCatalog(typeof(Program).Assembly);
            _container = new CompositionContainer(catalog);

            var commandHandler = _container.GetExportedValue<CommandHandler>();
            Console.WriteLine(commandHandler.Handle("cmd1"));
            Console.WriteLine(commandHandler.Handle("cmd2"));

            while (true)
            {
                Console.ReadLine();
            }

        }
    }
     */

    /// <summary>
    /// MEF使用
    /// 命令执行接口
    /// http://www.cnblogs.com/prinsun/archive/2013/04/18/3029634.html
    /// </summary>
    public interface ICommand
    {
        //是否执行
        bool CanHandle(string command);
        //返回命令结果
        string Handle(string command);
    }

    /// <summary>
    /// 单例创建
    /// </summary>
    [Export, PartCreationPolicy(CreationPolicy.Shared)]
    public sealed class CommandHandler
    {

        [ImportMany]
        private IEnumerable<ICommand> _handleCommandList;

        private CommandHandler() { }

        public string Handle(string command)
        {
            foreach (var cmd in _handleCommandList)
            {
                if (cmd.CanHandle(command))
                    return cmd.Handle(command);
            }
            return string.Empty;
        }
    }

    /// <summary>
    /// 命令抽象基类
    /// </summary>
    [InheritedExport(typeof(ICommand))]
    public abstract class CommandBase : ICommand
    {
        public abstract bool CanHandle(string command);
        public abstract string Handle(string command);
    }

    public class CommandAB : CommandBase
    {
        public override bool CanHandle(string command)
        {
            return command == "cmd1" || command == "cmd2";
        }

        public override string Handle(string command)
        {
            if (command == "cmd1")
                return "CommandA";
            else
                return "CommandB";
        }
    }
}
